import IconBiliBili from '@/components/icon/IconBiliBili';
import IconDouyin from '@/components/icon/IconDouyin';
import IconKuaishou from '@/components/icon/IconKuaishou';
import IconToutiao from '@/components/icon/IconToutiao';
import IconWeChatChannels from '@/components/icon/IconWeChatChannels';
import IconWeChatOfficialAccount from '@/components/icon/IconWeChatOfficialAccount';
import IconWeibo from '@/components/icon/IconWeibo';
import {
  initSaveExhibitionRecord,
  saveExhibitionRecord,
  updateExhibitionRecord,
} from '@/services/api/api-assess-month-emphasize-exhibition';
import { CheckCircleOutlined, CheckCircleTwoTone } from '@ant-design/icons';
import {
  ModalForm,
  ProFormDatePicker,
  ProFormText,
  ProFormTextArea,
  ProList,
} from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { Button, Descriptions, Flex, message, Space, Tag, Typography } from 'antd';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
interface AddExhibitionRecordProps {
  id?: string;
  recordData: AssessMonthEmphasizeRecordData.SelectRecord;
  onRefurbish: () => void;
  onSave: () => void;
}
const AddExhibitionRecord: React.FC<AddExhibitionRecordProps> = ({
  id,
  recordData,
  onRefurbish,
  onSave,
}) => {
  const access = useAccess();

  const formRef = useRef<ProFormInstance>();

  /**
   * 提交窗口
   */
  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  const [initData, setInitDataState] = useState<AssessMonthEmphasizeExhibitionData.InitData>();
 
  const [rangeDateWeek, setRangeDateWeekState] = useState<string>();
  const [rangeDateMonth, setRangeDateMonthState] = useState<string>();

  /**
   * 禁用微信视频号url
   */
  const [disabledWxsphUrl, setDisabledWxsphUrl] = useState<boolean>(false);

  const [selectedProveRowKeys, setSelectedProveRowKeys] = useState<React.Key[]>([]);

  /**
   * 加载来源详情
   * @param key
   */
  const loadInitSaveExhibitionRecord = async () => {
    try {
      const response = await initSaveExhibitionRecord({
        id: id,
        recordId: recordData.id,
      });
      if (response.code === 0) {
        const data = response.data;
        setInitDataState(data);

        if (id) {
          formRef.current?.setFieldsValue({
            rangeDateWeek: dayjs(data?.rangeWeek?.startDate),
            name: data.name,
            sourceName: data.sourceName,
            url: data.url,
          });

          if (data?.rangeMonth != undefined) {
            formRef.current?.setFieldsValue({
              rangeDateMonth: dayjs(data?.rangeMonth?.startDate),
            });
          }

          setRangeDateWeekState(data?.rangeWeek?.name);
          setSelectedProveRowKeys([data.recordProveId]);
        }
      }
    } catch (error) {}
  };

  const verificationSubmit = (values: any) => {
    if (!(values.name !== undefined && values.name.length > 0)) {
      message.warning('请输入标题');
      return false;
    }

    if (!(values.sourceName !== undefined && values.sourceName.length > 0)) {
      message.warning('请输入发布单位');
      return false;
    }

    if (selectedProveRowKeys.length == 0) {
      message.warning('请选择平台');
      return false;
    }

    if (disabledWxsphUrl) {
      //开启 禁用上传微信视频号url
    } else {
      if (!(values.url !== undefined && values.url?.length > 0)) {
        message.warning('请填写链接');
        return false;
      }
      if (!values?.url?.startsWith('https')) {
        message.warning('请填写符合要求的链接');
        return false;
      }
    }

    if (!(rangeDateWeek !== undefined && rangeDateWeek.length > 0)) {
      message.warning('请选择周');
      return false;
    }

    return true;
  };

  return (
    <DrawerForm
      key="add_assess_exhibition_record"
      title={'设置三好作品'}
      drawerProps={{
        width: 650,
        maskClosable: false,
        destroyOnClose: true,
      }}
      layout="horizontal"
      formRef={formRef}
      trigger={<Button type="primary">设置三好作品</Button>}
      initialValues={{
        name: recordData.dataName,
      }}
      onOpenChange={(visible) => {
        if (visible) {
          loadInitSaveExhibitionRecord();
        }
      }}
      submitter={{
        submitButtonProps: {
          style: {
            display: 'none',
          },
        },
        render: (props, defaultDoms) => {
          return [
            ...defaultDoms,
            <Button
              key="button_release_state_discard"
              icon={<CheckCircleOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                const values = formRef.current?.getFieldsValue();

                if (!verificationSubmit(values)) {
                  return;
                }

                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_release_state_discard'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async (values) => {
                props.submit();
                return true;
              }}
            />,
          ];
        },
      }}
      onChange={(values: any) => {}}
      onFinish={async (values) => {
        if (!verificationSubmit(values)) {
          return false;
        }
        let response;
        if (id == undefined) {
          response = await saveExhibitionRecord({
            ...values,
            recordId: recordData.id,
            recordProveId: selectedProveRowKeys[0],
            rangeDateWeek: rangeDateWeek,
            rangeDateMonth: rangeDateMonth,
          });
        } else {
          response = await updateExhibitionRecord({
            ...values,
            id: id,
            recordId: recordData.id,
            recordProveId: selectedProveRowKeys[0],
            rangeDateWeek: rangeDateWeek,
            rangeDateMonth: rangeDateMonth,
          });
        }
        if (response.code === 0) {
          message.success('提交成功');
          onSave();
          return true;
        } else {
          return false;
        }
      }}
    >
      <Descriptions column={3}>
        <Descriptions.Item label="发布日期">{recordData?.dataReleaseTime}</Descriptions.Item>
      </Descriptions>
      <ProFormDatePicker.Month
        name="rangeDateWeek"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            周
          </>
        }
        fieldProps={{
          onChange(date, dateString) {
            setRangeDateWeekState(dateString as string);
          },
        }}
      />
      <ProFormDatePicker.Month
        name="rangeDateMonth"
        label={
          <>
            <span
              style={{
                marginLeft: 11,
              }}
            >
              月
            </span>
          </>
        }
        hidden={!rangeDateWeek}
        fieldProps={{
          onChange(date, dateString) {
            setRangeDateMonthState(dateString as string);
          },
        }}
        extra={'因为存在周跨月的情况，可设置该三好作品为哪月'}
      />
      {/* <ProFormDatePicker.Quarter
        name="dateQuarter"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            季度
          </>
        }
      />
      <ProFormDatePicker.Year
        name="dateYear"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            年度
          </>
        }
      /> */}
      <ProFormTextArea
        width="xl"
        name="name"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            标题
          </>
        }
        fieldProps={{
          showCount: true,
          allowClear: true,
          rows: 2,
          count: { show: true, max: 100 },
          style: { resize: 'none' },
        }}
      />
      <Descriptions column={1}>
        <Descriptions.Item label="媒体类型">{recordData?.datahubLevelName}</Descriptions.Item>
        <Descriptions.Item label="所属区域">{recordData?.areaName}</Descriptions.Item>
        <Descriptions.Item label="主管单位">
          {recordData?.appointSourceOrganizationNames.map((item) => (
            <Tag
              onClick={() => {
                formRef.current?.setFieldsValue({
                  sourceName: item,
                });
              }}
            >
              {item}
            </Tag>
          ))}
        </Descriptions.Item>
      </Descriptions>
      <ProFormText
        width="xl"
        name="sourceName"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            单位
          </>
        }
        fieldProps={{
          showCount: true,
          allowClear: true,
          count: { show: true, max: 100 },
          style: { resize: 'none' },
        }}
      />
      <ProFormTextArea
        width="xl"
        name="url"
        label={
          <>
            <span
              style={{
                color: '#ff4d4f',
                paddingRight: 4,
              }}
            >
              *
            </span>
            链接
          </>
        }
        fieldProps={{
          showCount: true,
          allowClear: true,
          rows: 4,
          count: { show: true, max: 300 },
          style: { resize: 'none' },
          disabled: disabledWxsphUrl,
        }}
        extra={
          <>
            <div>只能添加一个https开头的链接</div>
            <div>抖音链接一定要以https开头，结构：https://www.douyin.com/video/数字字符串</div>
            <div>微信视频号暂时不支持链接</div>
            <div>如该三好作品是微信视频号作品，可先提交后联系房一，进行后续的配置</div>
          </>
        }
      />
      <ProList<AssessMonthEmphasizeRecordData.ProveSo>
        toolBarRender={false}
        rowKey="id"
        showActions="hover"
        grid={{ gutter: 16, column: 1 }}
        headerTitle={false}
        dataSource={recordData?.proves}
        itemCardProps={{
          bodyStyle: {
            paddingTop: 0,
            paddingLeft: 12,
            paddingRight: 12,
            paddingBottom: 12,
          },
        }}
        rowSelection={{
          type: 'radio',
          selectedRowKeys: selectedProveRowKeys,
          onChange(selectedRowKeys, selectedRows: AssessMonthEmphasizeRecordData.ProveSo[], info) {
            setSelectedProveRowKeys(selectedRowKeys);

            if (selectedRows.length > 0) {
              const prove = selectedRows[0];

              const dataUrl = prove.dataUrl;

              setDisabledWxsphUrl(prove.datahubChannelName == '微信视频号');

              formRef.current?.setFieldsValue({
                url: dataUrl,
              });
            }
          },
        }}
        metas={{
          title: {
            render: (
              dom: React.ReactNode,
              entity: AssessMonthEmphasizeRecordData.ProveSo,
              index: number,
              action,
            ) => {
              let icon;
              if (entity.datahubChannelName == '微信公众号') {
                icon = <IconWeChatOfficialAccount width={15} height={15} />;
              } else if (entity.datahubChannelName == '微信视频号') {
                icon = <IconWeChatChannels width={15} height={15} />;
              } else if (entity.datahubChannelName == '微博') {
                icon = <IconWeibo width={15} height={15} />;
              } else if (entity.datahubChannelName == '抖音') {
                icon = <IconDouyin width={15} height={15} />;
              } else if (entity.datahubChannelName == '今日头条') {
                icon = <IconToutiao width={15} height={15} />;
              } else if (entity.datahubChannelName == '快手') {
                icon = <IconKuaishou width={15} height={15} />;
              } else if (entity.datahubChannelName == '哔哩哔哩') {
                icon = <IconBiliBili width={15} height={15} />;
              } else if (entity.datahubChannelName == '网站') {
                icon = <IconToutiao width={15} height={15} />;
              } else if (entity.datahubChannelName == '客户端') {
                icon = <IconToutiao width={15} height={15} />;
              }
              return (
                <Space align={'center'}>
                  <Tag color={entity.appointSourceType == 1 ? 'gold' : 'green'}>
                    {entity.appointSourceType == 1 ? '官方' : '轻骑兵'}
                  </Tag>
                  <Flex justify={'center'} align={'center'}>
                    {icon}
                    <span
                      style={{
                        // marginTop: 2,
                        marginLeft: 5,
                      }}
                    >
                      {entity.datahubSourceName}
                    </span>
                  </Flex>
                </Space>
              );
            },
          },
          content: {
            render: (
              dom: React.ReactNode,
              entity: AssessMonthEmphasizeRecordData.ProveSo,
              index: number,
              action,
            ) => {
              return (
                <div>
                  <Descriptions
                  // column={4}
                  >
                    {entity.datahubChannelName == '微信公众号' ||
                    entity.datahubChannelName == '微博' ||
                    entity.datahubChannelName == '今日头条' ? (
                      <Descriptions.Item label="阅读量">{entity?.dataReadCount}</Descriptions.Item>
                    ) : (
                      <Descriptions.Item label="播放量">{entity?.dataPlayCount}</Descriptions.Item>
                    )}
                    <Descriptions.Item label="点赞量">{entity?.dataLikeCount}</Descriptions.Item>
                    <Descriptions.Item label="转发量">{entity?.dataCollectCount}</Descriptions.Item>
                  </Descriptions>
                  {entity.dataUrl && (
                    <Typography.Paragraph
                      style={{}}
                      copyable={{
                        text: async () =>
                          new Promise((resolve) => {
                            resolve(entity.dataUrl);
                          }),
                      }}
                    >
                      <blockquote>{entity.dataUrl}</blockquote>
                    </Typography.Paragraph>
                  )}
                </div>
              );
            },
          },
        }}
      />
    </DrawerForm>
  );
};

export default AddExhibitionRecord;
